<?php

namespace app\common\controller;

use app\common\model\PushTask as PushTaskModel;
use think\facade\View;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;
use app\common\variable\MsgCode;
use app\common\validate\Company as CompanyValidate;
use app\common\validate\CompanyContent as CompanyContentValidate;
use think\exception\ValidateException;
use app\common\model\Jobs as JobsModel;
use app\common\model\Company as CompanyModel;
use app\common\model\CompanyContent as CompanyContentModel;
use app\common\model\CompanyExecutives as CompanyExecutivesModel;
use app\common\model\CompanyDevelopmentHistory as CompanyDevelopmentHistoryModel;
use app\common\model\CompanyDemeanor as CompanyDemeanorModel;
use app\common\model\CompanyBrowse as CompanyBrowseModel;
use app\common\model\CompanyCollection as CompanyCollectionModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\controller\Posters as PostersController;
use app\common\model\Area as AreaModel;
use app\common\model\CompanyLogoExamine as CompanyLogoExamineModel;
use helper\Geohash;
use gaode\Gaode;
use gaode\request\Geocode;
use helper\Wechat;

/**
 * 
 */
class Company extends Base
{
    public static function saveCompany($D)
    {
        /**
         * 公司基本信息验证
         */
        try {
            validate(CompanyValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        }
        if (!empty($D['company_website'])) {
            if (
                strpos($D['company_website'], 'http://') === false
                && strpos($D['company_website'], 'https://') === false
            )
                $D['company_website'] = 'http://' . $D['company_website'];
        }
        /**
         * 公司拓展信息验证
         */
        try {
            validate(CompanyContentValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        }
        if (empty($D['uid']))
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        $uid = $D['uid'];
        if (!$uid)
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        /**
         * 公司基本信息
         */
        if(CompanyModel::onlyTrashed()->where(['uid' => $D['uid']])->count())
            return parent::ajaxReturn('该企业已被移至回收站，请联系客服恢复', MsgCode::$error);
        $CompanyModel = CompanyModel::where(['uid' => $D['uid']])->find();
        if ($CompanyModel) {
            if ($CompanyModel->attestation != 3) {
                $CompanyModel->title        =   $D['title'];
                $CompanyModel->industry_id  =   $D['industry_id'];
            }
        } else {
            $CompanyModel = new CompanyModel;
            $CompanyModel->app_id = request()->ApiInfo['app_id'];
            $CompanyModel->refresh_time = time();
            $CompanyModel->title        =   $D['title'];
            $CompanyModel->industry_id  =   $D['industry_id'];
        }
        $CompanyModel->stitle           =   $D['stitle'];
        $CompanyModel->uid              =   $D['uid'];
        // $CompanyModel->logo             =   $D['logo'];

        $push=true;
        $AdminPushTaskModel=new PushTaskModel;
        $AdminPushTaskModel->event       =   'SystemWarning';
        $PushData=[
            'tpl'       =>'user_pictured_audit',
            'level'     =>'企业Logo审核通知',
            'range'     =>'后台',
            'time'      =>date('Y-m-d H:i:s'),
//            'msg'       =>"企业用户【{$CompanyModel->title}】提交了Logo，请审核。"
            'msg'       => "您有新的LOGO需要审核，企业用户:{$CompanyModel->title}(UID:{$CompanyModel->uid})上传了新LOGO，等待您的审核。"

        ];
        $AdminPushTaskModel->data        =  json_encode($PushData,JSON_UNESCAPED_UNICODE);

        if (empty($CompanyModel->id)){
            $push=false;
        }
        if ($CompanyModel->logo != $D['logo'] && $CompanyModel->id) {
            $existsLogoExamine = CompanyLogoExamineModel::where('company_id', $CompanyModel->id)->where('status', 0)->find();
            if ($existsLogoExamine) {
                $existsLogoExamine->status = 2;
                $existsLogoExamine->reject_reason = '用户取消本次更改';
                $existsLogoExamine->save();
                $push=false;
            }
            $companyLogoExamineData = [
                'company_id' => $CompanyModel->id,
                'before_logo' => $CompanyModel->logo,
                'after_logo' => $D['logo'],
                'status' => 0
            ];
           $CompanyLogoExamine= CompanyLogoExamineModel::create($companyLogoExamineData);
        }else if (empty($CompanyModel->id)){
            $companyLogoExamineData = [
                'before_logo' => $CompanyModel->logo,
                'after_logo' => $D['logo'],
                'status' => 0
            ];
            $CompanyLogoExamine= CompanyLogoExamineModel::create($companyLogoExamineData);
        }
        if (empty($D['finance'])) {
            $CompanyModel->finance          =   0;
        } else {
            $CompanyModel->finance          =   $D['finance'];
        }
        $CompanyModel->nature           =   $D['nature'];
        $CompanyModel->region_id        =   $D['region_id'];
        $CompanyModel->size_type        =   $D['size_type'];
        $CompanyModel->registered_capital =   $D['registered_capital'];
        $CompanyModel->registered_capital_type =   $D['registered_capital_type'];
        if (!empty($D['corporate_welfare']))
            $CompanyModel->corporate_welfare =   implode(",", $D['corporate_welfare']);
        /**
         * 公司拓展信息
         */
        if ($CompanyModel) {
            $CompanyContentModel = CompanyContentModel::where(['cid' => $CompanyModel->id])->find();
            if (!$CompanyContentModel)
                $CompanyContentModel = new CompanyContentModel;
        } else {
            $CompanyContentModel = new CompanyContentModel;
        }
        $CompanyContentModel->contacts             =   trimall($D['contacts']);
        $CompanyContentModel->contacts_mobile      =   $D['contacts_mobile'];
        $CompanyContentModel->contacts_wechat      =   $D['contacts_wechat'];
        $CompanyContentModel->contacts_tel         =   $D['contacts_tel'];
        $CompanyContentModel->contacts_email       =   $D['contacts_email'];
        $CompanyContentModel->contacts_address     =   $D['contacts_address'];
        $CompanyContentModel->contacts_area1       =   $D['contacts_area'][1];
        $CompanyContentModel->contacts_area2       =   $D['contacts_area'][0];
        $CompanyContentModel->contacts_area3       =   $D['contacts_area'][2];
        $CompanyContentModel->company_website      =   $D['company_website'];
        $Geohash = new Geohash;
        if ($D['contacts_lng'] && $D['contacts_lat']) {
            $CompanyContentModel->contacts_lng         =   $D['contacts_lng'];
            $CompanyContentModel->contacts_lat         =   $D['contacts_lat'];
            $CompanyContentModel->contacts_geohash     =   $Geohash->encode($CompanyContentModel->contacts_lat, $CompanyContentModel->contacts_lng);
        } else {
            $CompanyContentModel->contacts_lng         =   null;
            $CompanyContentModel->contacts_lat         =   null;
            $CompanyContentModel->contacts_geohash     =   null;
            if (config('xy_map.server_status')) {
                $ProvinceModel = AreaModel::where(['id' => $CompanyContentModel->contacts_area2])->find();
                $CityModel = AreaModel::where(['id' => $CompanyContentModel->contacts_area1])->find();
                $AreaModel = AreaModel::where(['id' => $CompanyContentModel->contacts_area3])->find();
                try {
                    $Gaode = new Gaode;
                    $Geocode = new Geocode($Gaode->_config);
                    $Geocode->province = $ProvinceModel->title;
                    $Geocode->city = $CityModel->title;
                    $Geocode->area = $AreaModel->title;
                    $Geocode->address = $CompanyContentModel->contacts_address;
                    $ret = $Geocode->geo();
                    $location = explode(',', $ret->location);
                    $CompanyContentModel->contacts_lng         =   $location[0];
                    $CompanyContentModel->contacts_lat         =   $location[1];
                    $CompanyContentModel->contacts_geohash     =   $Geohash->encode($CompanyContentModel->contacts_lat, $CompanyContentModel->contacts_lng);
                } catch (\Exception $e) {
                }
            }
        }
        $CompanyContentModel->company_introduction =   $D['company_introduction'];
        $CompanyContentModel->company_descript     =   $D['company_descript'];
        if (!empty($D['template_id']))
            $CompanyContentModel->template_id          =   $D['template_id'];
        /**
         * 公司高管信息
         */
        if (!empty($D['executives'])) {
            if ($CompanyModel) {
                $CompanyExecutivesModel = CompanyExecutivesModel::where(['cid' => $CompanyModel->id])->find();
                if (!$CompanyExecutivesModel)
                    $CompanyExecutivesModel = new CompanyExecutivesModel;
            } else {
                $CompanyExecutivesModel = new CompanyExecutivesModel;
            }
            $CompanyExecutivesModel->executives            =   trimall($D['executives']);
            $CompanyExecutivesModel->executives_headimg    =   $D['executives_headimg'];
            $CompanyExecutivesModel->executives_job_title  =   $D['executives_job_title'];
            $CompanyExecutivesModel->executives_desc       =   $D['executives_desc'];
        }
        /*发展历程*/
        $CompanyDevelopmentHistoryList = [];
        if (!empty($D['development_history'])) {
            $CompanyDevelopmentHistoryModel = new CompanyDevelopmentHistoryModel;
            foreach ($D['development_history'] as $k => $v) {
                $CompanyDevelopmentHistoryList[$k] = [
                    'title'                 =>  $v['title'],
                    'desc'                  =>  $v['desc'],
                    'time'                  =>  round($v['time'] / 1000)
                ];
                if (!empty($v['id']))
                    $CompanyDevelopmentHistoryList[$k]['id'] = $v['id'];
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            $CompanyModel->save();
            $CompanyContentModel->cid = $CompanyModel->id;
            $CompanyContentModel->save();
            if (!empty($D['executives'])) {
                $CompanyExecutivesModel->cid = $CompanyModel->id;
                if (!empty($CompanyExecutivesModel->executives))
                    $CompanyExecutivesModel->save();
            }
            if (!empty($CompanyDevelopmentHistoryList)) {
                array_walk($CompanyDevelopmentHistoryList, function (&$v, $k) use ($CompanyModel) {
                    $v['cid'] = $CompanyModel->id;
                    krsort($v);
                });
                $CompanyDevelopmentHistoryModel->saveAll($CompanyDevelopmentHistoryList);
            }
            if (!empty($CompanyLogoExamine)){
                $CompanyLogoExamine->company_id=$CompanyModel->id;
                $push=true;
                $CompanyLogoExamine->save();
            }
            if ($push){
                $AdminPushTaskModel->uid = $uid;
                $AdminPushTaskModel->save();
            }


            // 提交事务
            Db::commit();
            Cache::set('updateUser:' . $CompanyModel->uid, true);
            return parent::ajaxReturn('保存成功', MsgCode::$success, CompanyModel::getEditFind($CompanyModel->id));
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
        }
    }
    public static function getCompanyInfo($id, $D = [])
    {
        $Field = [
            'company.id,company.title,company.stitle,company.logo,company.attestation,company.registered_capital,company.registered_capital_type,company.corporate_welfare,company.view',
            'nature.title as nature,finance.title as finance,size_type.title as size_type',
            'user_timer.online_time,user_timer.login_time',
            'industry.title as industry',
            'city.title as contacts_city,province.title as contacts_province,area.title as contacts_area',
            'content.contacts,content.contacts_mobile,content.contacts_wechat,content.contacts_tel,content.contacts_email,content.contacts_address,content.company_website,content.company_introduction,content.company_descript,content.template_id,content.contacts_lng,content.contacts_lat',
            'executives.executives,executives.executives_headimg,executives.executives_job_title,executives.executives_desc'
        ];
        $where = ['company.id' => $id];
        if (config('xy_company.is_forceattestation'))
            $where['company.attestation'] = 3;
        $is_admin = 0;
        if (isset($D['is_admin']) && $D['is_admin']) {
            $is_admin = 1;
            $where = ['company.id' => $id];
        }
        $Find = CompanyModel::alias('company')->where($where)
            ->where(['nature.alias' => 'company/nature'])
            ->where(['finance.alias' => 'company/finance'])
            ->where(['size_type.alias' => 'company/size_type'])
            ->join('user_timer user_timer', 'user_timer.uid = company.uid', 'LEFT')
            ->join('company_industry industry', 'industry.id = company.industry_id')
            ->join('company_content content', 'content.cid = company.id', 'LEFT')
            ->join('status_alias nature', 'nature.value=company.nature')
            ->join('status_alias finance', 'finance.value=company.finance')
            ->join('status_alias size_type', 'size_type.value=company.size_type')
            ->join('area province', 'province.id = content.contacts_area2')
            ->join('area city', 'city.id = content.contacts_area1')
            ->join('area area', 'area.id = content.contacts_area3')
            ->join('company_executives executives', 'executives.cid = company.id', 'LEFT')
            ->field(implode(",", $Field))
            ->withAttr('logo', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : config('web.imgurl') . config('xy_default_avatar.company_logo');
            })
            ->withAttr('executives', function ($v, $d) {
                return $v ? $v : '';
            })
            ->withAttr('executives_job_title', function ($v, $d) {
                return $v ? $v : '';
            })
            ->withAttr('executives_desc', function ($v, $d) {
                return $v ? $v : '';
            })
            ->withAttr('executives_headimg', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : config('web.imgurl') . config('xy_default_avatar.executives_headimg');
            })
            ->withAttr('business_license', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->withAttr('online_time', function ($v, $d) {
                return friendly_time($v, 'friendly');
            })
            ->withAttr('login_time', function ($v, $d) {
                return friendly_time($v, 'friendly');
            })
            ->withAttr('corporate_welfare', function ($v, $d) {
                $welfare = StatusAliasModel::where([['alias', '=', 'company/corporate_welfare'], ['value', 'in', arrtoint(explode(",", $v))]])->column('title');
                return $welfare;
            })->find();
        $Data = false;
        if ($Find) {
            $jobsWhere = [];
            if (config('xy_company.jobs_view_status'))
                $jobsWhere[] = ['examine', '=', 1];
            $Find->count_jobs = JobsModel::where($jobsWhere)->where(['company_id' => $Find->id, 'status' => 1])->count();
            $resume_sum = JobsDeliveryResumeModel::where(['company_id' => $Find->id])->count();
            $Find->delivery_resume = $resume_sum;
            $not_resume_sum = JobsDeliveryResumeModel::where(['company_id' => $Find->id, 'status' => 0])->count();
            $Find->resume_efficiency = ($resume_sum - $not_resume_sum) > 0 ? round(($resume_sum - $not_resume_sum) / $resume_sum * 100) : 0;
            $Find->is_collection = 0;

            $PostersModel = new \StdClass;
            $PostersModel->size = 140;
            $Find->qr_code = PostersController::CreateCompanyQRCode($Find, $PostersModel);
            $Find->shareData = [
                'type'  => 3,
                'id'    => $Find->id,
                'logo'  => $Find->logo,
                'title' => $Find->title . ' - ' . config('web.name'),
                'desc'  => $Find->company_introduction ? $Find->company_introduction : $Find->company_descript,
                'url'   => config('web.h5') . '/#/pageA/pages/common/company/company?id=' . $Find['id']
            ];
            $Data = $Find->toArray();
            if (!empty($D['resume_id']))
                $Data['is_collection'] = CompanyCollectionModel::where(['company_id' => $id, 'resume_id' => $D['resume_id']])->count();
            $Data['development_history'] = CompanyDevelopmentHistoryModel::where(['cid' => $id])
                ->withAttr('time', function ($v, $data) {
                    return date('Y-m-d', $v);
                })->field('title,desc,time')->select()->toArray();
            if (!empty(request()->AppInfo['app_modul']) && request()->AppInfo['app_modul'] == 'mobile' && request()->is_wx) {
                try {
                    $tinket = Wechat::getTicket();
                    if ($tinket) {
                        $url = config('web.h5') . '/';
                        $wxShareData = [
                            'noncestr' => Str::random(16),
                            'jsapi_ticket' => $tinket,
                            'timestamp' => time(),
                            'url' => $url
                        ];
                        ksort($wxShareData);
                        $wxShareData['signature'] = sha1(urldecode(http_build_query($wxShareData)));
                        $wxShareData['appid'] = config('xy_wechat_mp.appid') . '';
                        unset($wxShareData['jsapi_ticket']);
                        $Data['wxShareData'] = $wxShareData;
                    }
                } catch (\think\Exception $e) {
                }
            }
        }
        return $Data;
    }
    /**
     * 删除企业发展历程
     */
    public static function delDevelopmentHistory($D)
    {
        if (empty($D['id']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]', MsgCode::$error);
        $company_id = $D['company_id'];
        if (!$company_id)
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        $Model = new CompanyDevelopmentHistoryModel;
        $Data = $Model->where(['id' => $D['id'], 'cid' => $company_id])->field('id')->find();
        if ($Data) {
            if ($Model::destroy($Data->id)) {
                return parent::ajaxReturn();
            } else return parent::ajaxReturn('删除失败，请刷新重试', MsgCode::$error);
        } else return parent::ajaxReturn('数据不存在', MsgCode::$error);
    }
    /**
     * 保存企业风采
     */
    public static function saveDemeanor($D)
    {
        $CompanyDemeanorModel = new CompanyDemeanorModel;
        $CompanyDemeanorList = [];
        if (!empty($D['demeanor'])) {
            foreach ($D['demeanor'] as $k => $v) {
                $CompanyDemeanorList[$k] = [
                    'cid'                   =>  $D['company_id'],
                    'title'                 =>  $v['title'],
                    'path'                  =>  $v['path'],
                ];
                if ($v['id'])
                    $CompanyDemeanorList[$k]['id'] = $v['id'];
            }
        }
        if (!empty($CompanyDemeanorList)) {
            if ($CompanyDemeanorModel->saveAll($CompanyDemeanorList)) {
                return parent::ajaxReturn('保存成功');
            } else return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
        } else return parent::ajaxReturn('数据为空，保存失败', MsgCode::$error);
    }
    /**
     * 保存企业风采备注
     */
    public static function saveDemeanorTitle($D)
    {
        if (empty($D['id']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]', MsgCode::$error);
        $company_id = $D['company_id'];
        if (!$company_id)
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        $Model = CompanyDemeanorModel::where(['id' => $D['id'], 'cid' => $company_id])->find();
        $Model->title = $D['title'];
        if ($Model->save()) {
            return parent::ajaxReturn();
        } else return parent::ajaxReturn('保存失败，请重试', MsgCode::$error);
    }
    /**
     * 删除企业风采照片
     */
    public static function delCompanyDemeanor($D)
    {
        if (empty($D['id']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]', MsgCode::$error);
        $company_id = $D['company_id'];
        if (!$company_id)
            return parent::ajaxReturn('请先登录', MsgCode::$login);
        $Model = new CompanyDemeanorModel;
        $Data = $Model->where(['id' => $D['id'], 'cid' => $company_id])->field('id')->find();
        if ($Data) {
            if ($Model::destroy($Data->id)) {
                return parent::ajaxReturn();
            } else return parent::ajaxReturn('删除失败，请刷新重试', MsgCode::$error);
        } else return parent::ajaxReturn('数据不存在', MsgCode::$error);
    }
    public static function getCompanyList($D = [])
    {
        $where = [];
        if (!empty($D['key']))
            $where[] = ['c.title', 'like', '%' . $D['key'] . '%'];
        if (!empty($D['province']))
            $where[] = ['content.contacts_area2', '=', intval($D['province'])];
        if (!empty($D['city']))
            $where[] = ['content.contacts_area1', '=', intval($D['city'])];
        if (!empty($D['area']))
            $where[] = ['content.contacts_area3', '=', intval($D['area'])];
        if (!empty($D['industry']) && $D['industry'])
            $where[] = ['c.industry_id', '=', intval($D['industry'])];
        if (!empty($D['size_type']) && $D['size_type'])
            $where[] = ['c.size_type', '=', intval($D['size_type'])];
        if (!empty($D['finance']) && $D['finance'])
            $where[] = ['c.finance', '=', intval($D['finance'])];
        if (!empty($D['is_famous']) && $D['is_famous'] != 0)
            $where[] = ['c.is_famous', '=', intval($D['is_famous'])];
        if (!empty($D['welfare']))
            $where[] = ['c.corporate_welfare', 'like', '%' . $D['welfare'] . '%'];
        $Geohash = null;
        if ((!empty($D['lng']) && !empty($D['lat']))
            || (isset(request()->lng) && isset(request()->lat))
        ) {
            $Geohash = new Geohash;
            if (!empty($D['lng']) && !empty($D['lat'])) {
                $Geohash->lng = $D['lng'];
                $Geohash->lat = $D['lat'];
                $hash = $Geohash->encode($D['lat'], $D['lng']);
            } else {
                $Geohash->lng = request()->lng;
                $Geohash->lat = request()->lat;
                $hash = $Geohash->encode(request()->lat, request()->lng);
            }
            $range = 6;
            if (!empty($D['range'])) {
                switch (strtolower($D['range'])) {
                    case '1km':
                        $range = 6;
                        break;
                    case '3km':
                        $range = 5;
                        break;
                }
            }
            if ($hash)
                $where[] = ['content.contacts_geohash', 'like', substr($hash, 0, $range) . '%'];
        }
        $sort = 'c.is_famous desc,c.attestation desc,c.refresh_time desc,c.id desc';
        if (!empty($D['prop'])) {
            switch ($D['prop']) {
                case 'update_time':
                    $sort = 'c.update_time desc,c.id desc';
                    break;
                case 'defaultasc':
                    $sort = 'c.is_famous desc,c.attestation desc,c.refresh_time asc,c.id asc';
                    break;
                case 'update_timeasc':
                    $sort = 'c.update_time asc,c.id asc';
                    break;
                case 'recommend':
                    $sort = 'c.refresh_time desc,c.id desc';
                    break;
                case 'rand':
                    $sort = 'c.refresh_time desc,c.id rand()';
                    break;
            }
        }
        $Field = [
            'c.id,c.title,c.stitle,c.logo,c.attestation',
            'content.contacts_lng,content.contacts_lat',
            'industry.title as industry',
            'province.title as contacts_province',
            'city.title as contacts_city',
            'area.title as contacts_area',
            'size_type.title as size_type',
            'finance.title as finance',
            'nature.title as nature'
        ];
        if (isset(request()->sub_industry))
            $where[] = ['c.industry_id', '=', request()->sub_industry];
        if (isset(request()->sub_province))
            $where[] = ['content.contacts_area2', '=', request()->sub_province];
        if (isset(request()->sub_city))
            $where[] = ['content.contacts_area1', '=', request()->sub_city];
        if (isset(request()->sub_area))
            $where[] = ['content.contacts_area3', '=', request()->sub_area];

        if (config('xy_company.is_forceattestation'))
            $where[] = ['c.attestation', '=', 3];
        $CompanyModel = CompanyModel::alias('c')
            ->where(['user.status' => 1])
            ->where($where);
        if (!empty($D['uid'])) {
            $CompanyModel->where('c.uid', 'NOTIN', function ($query) use ($D) {
                $query->name('resume_blacklist')->where(['uid' => $D['uid']])->field('to_uid');
            });
            $CompanyModel->where('c.uid', 'NOTIN', function ($query) use ($D) {
                $query->name('company_blacklist')->where(['to_uid' => $D['uid']])->field('uid');
            });
        }
        $Data = $CompanyModel->where(['size_type.alias' => 'company/size_type'])
            ->where(['nature.alias' => 'company/nature'])
            ->join('user user', 'user.id=c.uid')
            ->join('company_content content', 'content.cid=c.id')
            ->join('company_industry industry', 'industry.id=c.industry_id')
            ->join('status_alias size_type', 'size_type.value=c.size_type')
            ->join('status_alias nature', 'nature.value=c.nature')
            ->where(['finance.alias' => 'company/finance'])
            ->join('status_alias finance', 'finance.value=c.finance')
            ->join('area province', 'province.id = content.contacts_area2')
            ->join('area city', 'city.id = content.contacts_area1')
            ->join('area area', 'area.id = content.contacts_area3')
            ->order($sort)
            ->field(implode(",", $Field))->paginate(16)
            ->each(function ($item, $key) use ($D, $Geohash) {
                $item['jobs_sum'] = JobsModel::where(['company_id' => $item['id'], 'status' => 1])->count();
                $item['jobs'] = JobsModel::where(['company_id' => $item['id'], 'status' => 1])->select();
                $item['logo'] = $item['logo'] ? config('web.imgurl') . $item['logo'] : config('web.imgurl') . config('xy_default_avatar.company_logo');
                $resume_sum = JobsDeliveryResumeModel::where(['company_id' => $item['id']])->count();
                $not_resume_sum = JobsDeliveryResumeModel::where(['company_id' => $item['id'], 'status' => 0])->count();
                $item['resume_efficiency'] = ($resume_sum - $not_resume_sum) > 0 ? round(($resume_sum - $not_resume_sum) / $resume_sum * 100) : 0;
                if ($Geohash)
                    $item->distance = $Geohash->getDistance($item->contacts_lat, $item->contacts_lng, $Geohash->lat, $Geohash->lng);
                return $item;
            });
        return $Data;
    }
    public static function getSelect($D = [])
    {
        $where = [];
        if (!empty($D['key']))
            $where[] = ['c.title', 'like', '%' . $D['key'] . '%'];
        if (!empty($D['city']))
            $where[] = ['content.contacts_area2', '=', intval($D['city'])];
        if (!empty($D['industry']) && $D['industry'])
            $where[] = ['c.industry_id', '=', intval($D['industry'])];
        if (!empty($D['size_type']) && $D['size_type'])
            $where[] = ['c.size_type', '=', intval($D['size_type'])];
        if (!empty($D['finance']) && $D['finance'])
            $where[] = ['c.finance', '=', intval($D['finance'])];
        if (!empty($D['is_famous']) && $D['is_famous'] != 0)
            $where[] = ['c.is_famous', '=', intval($D['is_famous'])];
        $sort = 'c.is_famous desc,c.attestation desc,c.refresh_time desc,c.id desc';
        if (!empty($D['prop'])) {
            switch ($D['prop']) {
                case 'update_time':
                    $sort = 'c.update_time desc,c.id desc';
                    break;
                case 'defaultasc':
                    $sort = 'c.is_famous desc,c.attestation desc,c.refresh_time asc,c.id asc';
                    break;
                case 'update_timeasc':
                    $sort = 'c.update_time asc,c.id asc';
                    break;
                case 'recommend':
                    $sort = 'c.refresh_time desc,c.id desc';
                    break;
                case 'rand':
                    $sort = 'c.refresh_time desc,c.id rand()';
                    break;
            }
        }
        $Field = [
            'c.id,c.title,c.stitle,c.logo,c.id as jobs_sum,c.id as resume_efficiency',
            'industry.title as industry',
            'area.title as contacts_area',
            'size_type.title as size_type',
            'finance.title as finance',
            'nature.title as nature'
        ];
        if (isset(request()->sub_industry))
            $where[] = ['c.industry_id', '=', request()->sub_industry];
        if (isset(request()->sub_province))
            $where[] = ['content.contacts_area2', '=', request()->sub_province];
        if (isset(request()->sub_city))
            $where[] = ['content.contacts_area1', '=', request()->sub_city];
        if (isset(request()->sub_area))
            $where[] = ['content.contacts_area3', '=', request()->sub_area];
        if (config('xy_company.is_forceattestation'))
            $where[] = ['c.attestation', '=', 3];
        $CompanyModel = CompanyModel::alias('c')
            ->where(['user.status' => 1])
            ->where($where);
        if (!empty($D['uid'])) {
            $CompanyModel->where('c.uid', 'NOTIN', function ($query) use ($D) {
                $query->name('resume_blacklist')->where(['uid' => $D['uid']])->field('to_uid');
            });
            $CompanyModel->where('c.uid', 'NOTIN', function ($query) use ($D) {
                $query->name('company_blacklist')->where(['to_uid' => $D['uid']])->field('uid');
            });
        }
        $Data = $CompanyModel->where(['size_type.alias' => 'company/size_type'])
            ->where(['nature.alias' => 'company/nature'])
            ->join('user user', 'user.id=c.uid')
            ->join('company_content content', 'content.cid=c.id')
            ->join('company_industry industry', 'industry.id=c.industry_id')
            ->join('status_alias size_type', 'size_type.value=c.size_type')
            ->join('status_alias nature', 'nature.value=c.nature')
            ->where(['finance.alias' => 'company/finance'])
            ->join('status_alias finance', 'finance.value=c.finance')
            ->join('area area', 'area.id = content.contacts_area2')
            ->order($sort)
            ->field(implode(",", $Field))->limit($D['length'])
            ->withAttr('jobs_sum', function ($v, $data) {
                return JobsModel::where(['company_id' => $v, 'status' => 1])->count();
            })
            ->withAttr('logo', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : config('web.imgurl') . config('xy_default_avatar.company_logo');
            })
            ->withAttr('resume_efficiency', function ($v, $data) {
                $resume_sum = JobsDeliveryResumeModel::where(['company_id' => $v])->count();
                $not_resume_sum = JobsDeliveryResumeModel::where(['company_id' => $v, 'status' => 0])->count();
                return ($resume_sum - $not_resume_sum) > 0 ? round(($resume_sum - $not_resume_sum) / $resume_sum * 100) : 0;
            })
            ->select();
        foreach ($Data as $item) {
            $item->jobs_salary_show_type = config('xy_company.jobs_salary_show_type');
            $item->jobs_list = JobsModel::where(['company_id' => $item->id])->field('id,title,salary_min,salary_max')->select();
        }
        return $Data;
    }
    public static function getCompanyBrowseList($company_id, $where = [])
    {
        $CompanyBrowseModel = CompanyBrowseModel::alias('b')->where(['b.company_id' => $company_id])
            ->where($where)
            ->whereNull('b.delete_time')
            ->where(['edu.alias' => 'resume/educational_background'])
            ->join('resume resume', 'resume.id=b.resume_id')
            ->join('resume_employment_intention e', 'e.resume_id=resume.id AND e.default=1', 'LEFT')
            ->join('status_alias edu', 'edu.value=resume.educational_background')
            ->order('b.id desc')
            ->field('b.*,resume.name,resume.sex,resume.age,resume.work_experience_time,edu.title as educational_background,e.salary_min,e.salary_max')->paginate(15)
            ->each(function ($item, $key) use ($company_id) {
                $item->jobs_salary_show_type = config('xy_company.jobs_salary_show_type');
                $item->friendly_create_time = friendly_time($item['create_time'], 'friendly');
                return $item;
            });
        return $CompanyBrowseModel;
    }
    public static function toggleCompanyCollection($D)
    {
        $CompanyCollectionModel = CompanyCollectionModel::where(['resume_id' => $D['resume_id'], 'company_id' => $D['company_id']])->find();
        if ($CompanyCollectionModel) {
            if ($CompanyCollectionModel->delete()) {
                return parent::ajaxReturn('已取消关注');
            } else return parent::ajaxReturn('取消关注失败，请重试', MsgCode::$error);
        } else {
            $CompanyCollectionModel = new CompanyCollectionModel;
            $CompanyCollectionModel->resume_id = $D['resume_id'];
            $CompanyCollectionModel->company_id = $D['company_id'];
            if ($CompanyCollectionModel->save()) {
                return parent::ajaxReturn('已关注');
            } else return parent::ajaxReturn('关注失败，请重试', MsgCode::$error);
        }
    }
    public static function getSearchCompany($D)
    {
        $CompanyModel = CompanyModel::where('title|stitle', 'like', '%' . $D['key'] . '%')->where('uid', 'NOTIN', function ($query) use ($D) {
            $query->name('resume_blacklist')->where(['uid' => $D['uid']])->field('to_uid');
        })->field('uid,title')->limit(10)->select();
        if ($CompanyModel) {
            return parent::ajaxReturn('', MsgCode::$success, $CompanyModel);
        } else {
            return parent::ajaxReturn('暂无数据', MsgCode::$error);
        }
    }
}
